import heapq
class Node:
    def __init__(self,val,fre):
        self.val = val
        self.fre = fre
    def __str__(self):
        return str(self.val)+":"+str(self.fre)
    def __lt__(self, other):
        if self.fre >= other.fre:
            return False
        else:
            return True

class Solution:
    def topKFrequent(self, nums, k: int):
        hash1 = {}
        for i in nums:
            if i not in hash1:
                hash1[i] = 0
            hash1[i] = hash1[i] + 1
        h = []
        for key in hash1:
            time = hash1[key]
            if len(h) < k:
                heapq.heappush(h, Node(key, time))
            else:
                if h[0].fre < time:
                    heapq.heappush(h, Node(key, time))
                if len(h) > k:
                    heapq.heappop(h)
        return [node.val for node in h]

if __name__ == '__main__':
    so = Solution()
    nums = [1,1,1,2,2,3]
    k = 2
    r = so.topKFrequent(nums, k)
    print(r)
